<template>
<div class="rx-app-use-container">
    <div class="rx-app-list-content">
        <div class="rx-os-search-input" >
            <a-input-group compact>
                <a-input class="rx-os-input" :value="searchText" @change="searchChange" placeholder="搜索应用" allowClear />
                <a-button @click="handleSearch" type="primary" ><my-icon type="iconsearch"/></a-button>
            </a-input-group>
        </div>
        <div class="rx-app-use-search-box">
            <p>Hi，您可以在下方查看您的全部应用~</p>
        </div>
        <div class="rx-app-roll">
            <a-tabs class="rx-app-tabs rx-a-tabs" v-model="tabActiveKey" :tabBarGutter="0" :animated="false">
                <template  v-for="obj of (searchData.length > 0? searchData:appList)">
                    <a-tab-pane :key="obj.key" :tab="getName(obj)" :disabled="obj.apps.length === 0">
                        <div class="rx-app-list">
                            <template v-for="app of pageData(obj)">
                                <div class="rx-app-item" :key="app.appId">
                                    <div class="rx-app-title-box">
                                        <span class="rx-app-icon" :style="{'backgroundColor':app.backColor}">
                                            <my-icon :type="getIcon(app.icon).icon" v-if="getIcon(app.icon).state" />
                                            <a-icon :type="getIcon(app.icon).icon" v-else/>
                                        </span>
                                        <div class="rx-app-title"  :title="getAppName(app.title || app.clientName)">{{ getAppName(app.title || app.clientName) }}</div>
                                        <div class="rx-app-favorite"
                                             @click="handleFavorite(app)"
                                             :class="{'rx-app-favorite-yes':favoriteAppKeys.includes(app.appId)}"
                                        >
                                            <my-icon type="iconxingshi"/>
                                        </div>
                                    </div>
                                    <div class="rx-app-describe" :title="app.descp">{{app.descp?app.descp:'暂无描述'}}</div>
                                    <div class="rx-app-state-box">
                                        <span class="rx-app-state" :style="getColor(app)">
                                            {{getClassName(app)}}
                                        </span>
                                        <div class="rx-app-extend-btn" @click="appPreview(app)">
                                            进入应用<span>&gt;</span>
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </div>
                        <div class="rx-app-page-box">
                            <a-pagination v-model="obj.page" size="small" :total="obj.apps.length" :pageSize="obj.pageSize" />
                        </div>
                    </a-tab-pane>
                </template>
            </a-tabs>
        </div>
    </div>
</div>
</template>

<script>
import {mapState,mapMutations} from 'vuex';
import SysAppApi from "@/api/system/core/sysApp";
import SysAppFavoritesApi from "@/api/system/core/sysAppFavorites";
import appPreview from "@/layouts/AppDesignPage/appPreview";
export default {
    name: "ApplicationUse",
    mixins:[appPreview],
    computed: {
        ...mapState({
            menus: state => state.appSetting.menus
        }),
        language(){
            return window.localStorage.getItem('language') || 'zh-CN';
        },
        pageData(){
            return (obj)=>{
                let {page,pageSize} = obj ;
                if(obj.apps.length === 0){
                    return []
                }
                return obj.apps.slice((page-1)*pageSize,page*pageSize)
            }
        },
        getClassName(){
            return (app)=>{
                return this.getAppName(this.dataClass[app.categoryId].title)
            }
        },
        getColor(){
            return (app)=>{
                return this.dataClass[app.categoryId].color ;
            }
        }
    },
    data(){
        return {
            tabActiveKey:'all',
            pageSize:15,
            appList:[],
            searchData:[],
            searchText:'',
            dataClass:{},//存储应用分类
            colors:[//颜色
                {background:'#e8f7ff',color:'#2387fa'},
                {background:'#e8f3ff',color:'#2a78fa'},
                {background:'#eaedff',color:'#2a48ff'},
                {background:'#ffece8',color:'#f42928'},
                {background:'#fff3e8',color:'#f55a12'},
                {background:'#fff7e8',color:'#ff7a22'},
                {background:'#fffce8',color:'#f5a700'},
                {background:'#e8ffea',color:'#00a200'},
                {background:'#e8fffb',color:'#00bdbf'},
                {background:'#f1ffe4',color:'#95d708'},
                {background:'#f5e8ff',color:'#7816ff'},
                {background:'#ffe8fb',color:'#d300d4'},
                {background:'#ffe8f1',color:'#f30e8d'}
            ],
            favoriteAppKeys:[],//收藏的应用id
        }
    },
    created(){
        this.initApps()
    },
    methods:{
        searchChange(e){
            let { value } =e.target ;
            if(!value){
                this.searchText = '' ;
                this.searchData = []
            }else {
                this.searchText = value;
            }
        },
        handleSearch(){
            let self = this ;
            this.searchData=this.appList.map(item=>{
                let apps = item.apps.filter(app=>{
                    return self.getAppName(app.title || app.clientName).includes(self.searchText)
                })
                return {
                    ...item,
                    page:1,
                    apps
                }
            })
        },
        //收藏应用
        Collecting(app){
            let parameter = {
                appId:app.appId
            }
            let self = this;
            SysAppFavoritesApi.addFavorite(parameter).then(res=>{
                if(res.success){
                    self.favoriteAppKeys.push(app.appId);
                    let collectApps = self.appList.find(item=>item.key==='collectApps');
                    collectApps.apps.push(app)
                }
            })
        },
        //取消收藏应用
        cancelFavorite(app){
            let parameter = { appId:app.appId }
            let self = this;
            SysAppFavoritesApi.cancelFavorite(parameter).then(res=>{
                if(res.success){
                    let idx = this.favoriteAppKeys.findIndex(key=>key === app.appId);
                    self.favoriteAppKeys.splice(idx,1);
                    let collectApps = self.appList.find(item=>item.key==='collectApps');
                    let appIdx = collectApps.apps.findIndex(item=>item.appId === app.appId);
                    collectApps.apps.splice(appIdx,1)
                }
            })
        },
        handleFavorite(app){
            if(this.favoriteAppKeys.includes(app.appId)){
                //取消收藏
                this.cancelFavorite(app)
            }else {
                //收藏
                this.Collecting(app)
            }
        },
        async favorite(){
            //获取全部收藏应用
           return SysAppFavoritesApi.getFavoritesApps()
        },
        async getRecentlyUsedApps(){
            //获取全部最近使用应用
            return SysAppFavoritesApi.getLastUseApps()
        },
        async setApps(classList){
            let allApps = SysAppApi.getByCategoryOrKey({CID:'-1'});
            let favoriteApp = this.favorite()
            let recentlyUsedApps = this.getRecentlyUsedApps();
            let res = await Promise.all([favoriteApp,recentlyUsedApps,allApps]);
            let obj = {
                all:res[2].data,//全部应用
                collectApps:res[0].data,//收藏应用
                recentlyUsed:res[1].data//最近使用
            }
            //存储收藏的appId
            let favoriteKeys = []
            if(res[0].data.length > 0){
                for (let item of res[0].data){
                    if(!favoriteKeys.includes(item.appId)){
                        favoriteKeys.push(item.appId)
                    }
                }
                this.favoriteAppKeys = favoriteKeys ;
            }

            //设置数据到对应的大类
            for (let cls of classList){
                cls.apps = obj[cls.key]
            }
            this.appList = classList ;
        },
        getClassList(){//设置tab分类
            let { pageSize } = this ;
            let obj = {
                all:'{ "zh-CN": "全部", "en-US": "All", "ja-JP": "全部です"}',
                collect:'{ "zh-CN": "收藏的应用", "en-US": "Favorite apps", "ja-JP": ""}',
                recently:'{ "zh-CN": "最近使用的应用", "en-US": "Recently used apps", "ja-JP": ""}'
            }
            let arr = [
                {key:'all',title:obj.all,apps:[],page:1,pageSize},
                {key:'collectApps',title:obj.collect,apps:[],page:1,pageSize},
                {key:'recentlyUsed',title:obj.recently,apps:[],page:1,pageSize}
            ]
            return arr ;
        },
        getRandomColor(){//获取随机颜色
            let colors = this.colors
            let random = Math.ceil(Math.random() * 14) - 1 ;
            return colors[random]
        },
        getColors(obj){
            let color = () =>{
                //当所有颜色全部被随机过，则进行重新一轮随机；
                let colors = [...this.colors];
                if(colors.length == 0){
                    colors = [...this.colors];
                }
                return function(){
                    let random = Math.ceil(Math.random() * colors.length) - 1 ;
                    let _color =  colors[random];
                    //删除已经选取过的颜色
                    colors.splice(random,1);
                    return _color ;
                }
            }
            let getColor = color();
            for (let key in obj){
                obj[key].color = getColor();
            }
        },
        initApps(){
            SysAppApi.getCountByCategory().then(res => {
                if(!res.success){
                    this.$message.error(res.message);
                    return ;
                }
                let { data }=res;

                let obj = {}
                data.forEach(item=>{
                    obj[item.CID] = {title:item.CNAME,color:{}}
                })
                //设置随机颜色
                this.getColors(obj);
                //存储所处app分类
                this.dataClass = obj ;

                //定义大类 全部应用 收藏应用 最近使用 三大类
                let classList =  this.getClassList();
                //设置大类下的app数据
                this.setApps(classList);
            });
        },

        getName(app){
            let name = this.getAppName(app.title || app.clientName)
            return `${name}(${app.apps.length})`
        },
        getAppName(name){
            let lang = this.language;
            try {
                let _name = new Function('return ' + name)();
                return _name[lang]
            }catch (e){
                return name ;
            }
        },
        getIcon(icon){
            let _icon = new Function('return ' +icon )();
            if(_icon.type){
                return {
                    state:['customIcon','userCustomIcon','jpaasIcon'].includes(_icon.type),
                    icon:_icon.icon
                }
            }
            return {state:false}
        },
    }
}
</script>

<style scoped>
.rx-app-roll{
    --appItem:5
}
.rx-app-use-search-box{
    padding: 15px;
    position: absolute;
    height: 90px;
    width: 100%;
    background:#fff url("../../assets/img/bg_yyzx.png");
    background-position:  top right;
    background-size: 100%;
    z-index: 1;
}
.rx-app-use-search-box > p{
    font-weight: bold;
}
.rx-app-use-container{
    height: 100%;
    padding: 10px;
    display: flex;
    flex-direction: column;
}
.rx-app-list-content{
    flex: 1;
    position: relative;
    background: #fff;
    border-radius: 4px;
}

.rx-app-btn-box button{
    margin-right: 10px;
}
.rx-app-roll{
    inset: 0;
    top: 46px;
    position: absolute;
    overflow: auto;
    z-index: 2;
}

.rx-app-list{
    padding:0 10px;
    overflow: auto;
    height: calc( 100% - 48px );
}

.rx-app-item{
    position: relative;
    display: inline-block;
    vertical-align: top;
    width: calc( ( 100% - var(--appItem) * 10px ) / var(--appItem) );
    margin:0 5px 10px;
    max-height: 142px;
    background-color: #ffffff;
    border-radius: 4px;
    border: solid 1px #e8e8e8;
    padding: 15px;
}

.rx-app-title-box{
    display: flex;
    align-items: center;
}
.rx-app-icon{
    display: flex;
    justify-content: center;
    align-items: center;
    width: 46px;
    height: 46px;
    background-color: #4285f4;
    border-radius: 8px;
    font-size: 24px;
    color: #fff;
    margin-right: 15px;
}
.rx-app-title{
    flex: 1;
    font-weight: bold;
    overflow: hidden;
    white-space:nowrap;
    text-overflow: ellipsis;
}
.rx-app-describe{
    overflow: hidden;
    white-space:nowrap;
    text-overflow: ellipsis;
    font-size: 12px;
    color: rgba(0,0,0,.65);
    padding:10px 0 ;
}
.rx-app-state-box{
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.rx-app-state{
    display: inline-block;
    padding: 0 8px;
    font-size: 12px;
    line-height: 22px;
    height: 22px;
    background-color: #e8ffea;
    border-radius: 2px;
    color: #00a200;
}
.rx-app-state.rx-app-state-paused{
    background-color: #f2f3f5;
    color: #6d7887;
}

.rx-app-extend-btn{
    white-space: nowrap;
    display: flex;
    align-items: center;
    padding-left: 6px;
    line-height: 24px;
    border-radius: 2px;
    font-size: 12px;
    position: relative;
    color: #4285f4;
}

.rx-app-roll >>> .ant-tabs-bar{
    margin-bottom: 0;
}
.rx-app-tabs >>> .ant-tabs-content{
    height: calc( 100% - 34px );
}
.rx-app-tabs >>> .ant-tabs-bar{
    border-bottom: 0;
}
.rx-app-tabs >>> .ant-tabs-nav-container{
    margin-bottom: 0;
}
.rx-app-tabs >>> .ant-tabs-nav-wrap{
    margin-bottom: 0;
    padding-bottom: 30px;
}
.rx-app-tabs >>> .ant-tabs-ink-bar{
    display: none!important;
}
.rx-app-tabs >>> .ant-tabs-tab{
    padding:  0 16px;
    line-height: 32px;
    height: 32px;
    font-size: 14px;
}
.rx-app-tabs >>> .ant-tabs-nav .ant-tabs-tab-active{
    background-color: #fff;
    border-radius: 16px;
    color: #4285f4;
}
.rx-app-page-box{
    padding: 6px 15px;
}

.rx-app-favorite{
    position: absolute;
    width: 24px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    right: 0;
    top: 0;
    color: #e6e5e5;
    cursor: pointer;
}
.rx-app-favorite.rx-app-favorite-yes{
    color: rgb(254, 149, 37);
}
.rx-os-search-input{
    position: absolute;
    top: 46px;
    right: 15%;
    z-index: 3;
}
.rx-os-input{
    width: 300px;
}
@media (max-width: 1200px) {
    .rx-app-roll{
        --appItem:4
    }
    .rx-os-search-input{
        right: 10%;
    }
}

@media (max-width: 1000px) {
    .rx-app-roll{
        --appItem:3
    }
    .rx-os-input{
        width: 200px!important;
    }
}
@media (max-width: 800px) {
    .rx-app-roll{
        --appItem:2
    }
    .rx-os-search-input{
        right: 6%;
    }
    .rx-os-input{
        width: 160px!important;
    }
}

</style>